package net.easyjava.third.db.utils;

import net.easyjava.third.db.annotation.Column;
import net.easyjava.third.db.annotation.ID;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by wxnacy on 16/6/29.
 */
public class DBCreate {
    private Class clazz;

    public DBCreate() {
    }

    public DBCreate(Class clazz) {
        this.clazz = clazz;
    }

    public String getSql() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        //INSERT INTO CATEGORY (id, cid, name, status, display_order) VALUES (?,?,?,?,?);
        StringBuffer sql = new StringBuffer("CREATE TABLE '");
        String tableName = DBUtils.getTableName(this.clazz);
        sql.append(tableName + "'(");

        StringBuffer col = new StringBuffer();



        Field[] fields = this.clazz.getDeclaredFields();
        String idFieldName = null;
        long begin = System.currentTimeMillis();
        for(Field field:fields){
            boolean flag = field.isAnnotationPresent(ID.class);
            String fieldName = field.getName();
            if(!"serialVersionUID".equalsIgnoreCase(fieldName)){
                String colName = DBUtils.getColumn(field);
                String type = field.getType().getSimpleName();
                Column column = field.getAnnotation(Column.class);
                String colType = null;
                switch (type){
                    case "Long":case "long":colType = "bigint";break;
                    case "int":case "Integer":colType = "int";break;
                    case "String":colType = "varchar";break;
                }
                col.append("`").append(colName).append("`").append(" ")
                        .append(colType).append("(").append(column.length()).append(")");


                if(flag){
                    ID id = field.getAnnotation(ID.class);
                    idFieldName = colName;
                    col.append(" NOT NULL ");
                    if(id.autoIncrement()){
                        col.append(" AUTO_INCREMENT");
                    }
                }else{
                    if(!column.allowNull()){
                        col.append(" NOT NULL ");

//                        col.append("DEFAULT ").append(column.defaultValue());
                    }
                }

                col.append(",");
            }
        }

        if(idFieldName != null){
            col.append("PRIMARY KEY (`").append(idFieldName).append("`)");
        }


        long end = System.currentTimeMillis();
        System.out.println("make sql = " + (end - begin));

        sql.append(col);
        sql.append(");");
        System.out.println("sql = " + sql);

        return sql.toString();
    }







}
